package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.util.JsonUtil;
import cn.tedu.order.util.RedisUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName OrderServiceImpl
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/7/1 11:47
 * @Version V1.0
 **/
@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;


    @Autowired
    private OrderMapper orderMapper;
    @Transactional //控制本地事务
    @GlobalTransactional //开启全局事务,只在第一个模块添加
    @Override
    public void create(Order order) {
        //生成订单id
        String s= easyIdClient.nextId("order_business");
        //包装类Long
        Long orderId = Long.valueOf(s);

        order.setId(orderId);
        orderMapper.create(order);


        //远程调用账户扣减账户金额
accountClient.decrease(order.getUserId(), order.getMoney());

        //远程调用库存减少商品库存
storageClient.decrease(order.getProductId(), order.getCount());

//在redis里也存一份订单数据
        redisUtil.set(""+orderId, JsonUtil.to(order));

    }

    @Override
    public Order findById(Long id) {

//         1.从redis 查询
        String json = (String) redisUtil.get("" + id);

//         2.如果数据存在直接返回
        if (json !=null){
            return JsonUtil.from(json, Order.class);
        }

//         3如果redis没有数据从数据库查询
        Order order = orderMapper.selectById(id);
//         4把数据加入redis缓存
        redisUtil.set(""+id, JsonUtil.to(order));
//         5返回
        return order;


    }
}
